import json
import copy
from typing import List
from typing import Union
from apis import api_routes
from sqlalchemy import desc
from sqlalchemy import and_
from flask import abort, g, request, jsonify
from models.users.roles import Roles as Rs
from models.users.users import Users as Us
from models.owner.owner import Owner
from security.decoration import certification
from public.sidebar import sidebars
from public.contexts import context_logs
from datetime import datetime
from public.local import local_date
from public.local import datetime_type
from datetime import timedelta
from public.local import nest


@api_routes.route("/owner", methods=["POST"])
@certification(auth=True, role="admin")
def func_owner_post_api():
    """
    添加班次API, 需要角色验证才能添加
    http://127.0.0.1:8080/api/owner
    Content-Type=application/json
    methods=["POST"]
    {
    "name":        string        ****    班次名字
    "start":       string        ****    开始时间  格式： %H:%M:%S
    "finish"       string        ****    结束时间  格式： %H:%M:%S
    }
    :return:
        {'status': 40001, 'msg': "这个角色已经存在"}
        {'status': 40002, 'msg': "角色描述已经存在"}
        {'status': 200, "msg": "添加角色成功"}
     ---
    tags:
      - 班次管理
    """
    data: dict = request.get_json()
    name: str = data.get("name")
    start: str = data.get("start")
    finish: str = data.get("finish")

    if name is None or start is None or finish is None:
        abort(400)
    db_owner: Union[Owner, None] = g.session.query(Owner).filter(Owner.name == name).first()
    if db_owner is not None:
        return jsonify({'status': 4000, 'data': "已经存在排班任务"})

    log_pram: dict = {
        "name": name,
        "start": start,
        "finish": finish
    }
    context_logs(name="班次管理", obsolescence=None, data=str(log_pram))

    g.session.add(Owner(
        name=name,
        start=start,
        finish=finish
    ))
    g.session.commit()
    return jsonify({'status': 200, "msg": "添加排班成功"})


@api_routes.route("/owner", methods=["GET"])
@certification(auth=True, role=None)
def func_owner_get_api():
    """
    获取排班任务, 不用做分页
    http://127.0.0.1:8080/api/owner
    Content-Type=application/x-www-form-urlencoded
    methods=["GET"]
    :return:
    ---
    tags:
      - 班次管理
    """
    data: List[Owner] = g.session.query(Owner).order_by(Owner.id).all()

    resp: list = []
    for index, itr in enumerate(data):
        temp_start = local_date() + " " + itr.start.strftime("%H:%M:%S")
        temp_finish = local_date() + " " + itr.finish.strftime("%H:%M:%S")

        temp_start1 = datetime.strptime(temp_start, "%Y-%m-%d %H:%M:%S")
        temp_finish1 = datetime.strptime(temp_finish, "%Y-%m-%d %H:%M:%S")

        if (temp_finish1 > temp_start1) is False:
            temp_finish = nest() + " " + itr.finish.strftime("%H:%M:%S")
            temp_finish1 = datetime.strptime(temp_finish, "%Y-%m-%d %H:%M:%S")

        running: bool = False
        if temp_start1 <= datetime_type() <= temp_finish1:
            running = True

        resp.append({
            "owner_id": itr.id,
            "name": itr.name,
            "start": itr.start.strftime("%H:%M:%S"),
            "finish": itr.finish.strftime("%H:%M:%S"),
            "running": running
        })

    return jsonify({'status': 200, 'data': resp})


@api_routes.route("/owner", methods=["PUT"])
@certification(auth=True, role="admin")
def func_owner_put_api():
    """
    更新排班API接口信息
    http://127.0.0.1:8080/api/owner
    Content-Type=application/json
    methods=["PUT"]
    {
    owner_id         int    *** 数据库ID, 数据库的，前端不用管
    name:        string     排班名称
    start:       string     开始时间  格式： %H:%M:%S
    finish        string    结束时间  格式： %H:%M:%S
    }
    :return:
    ---
    tags:
      - 班次管理
    """
    data: dict = request.get_json()
    owner_id: int = data.get("owner_id")
    name: Union[str, None] = data.get("name")
    start: Union[str, None] = data.get("start")
    finish: Union[str, None] = data.get("finish")

    if owner_id is None:
        abort(400)
    db_owner: Union[Owner, None] = g.session.query(Owner).filter(Owner.id == owner_id).first()
    if db_owner is None:
        return jsonify({'status': 4000, 'data': "排班不存在"})

    if name is not None and name != db_owner.name:
        db_owner2: Union[Owner, None] = g.session.query(Owner).filter(Owner.name == name).first()
        if db_owner2 is not None:
            return jsonify({'status': 4001, 'data': "排班名称已存在"})
        db_owner.name = name

    if start is not None and len(start) > 0:
        db_owner.start = start
    if finish is not None and len(finish) > 0:
        db_owner.finish = finish

    g.session.commit()
    return jsonify({'status': 200, "msg": "角色更新成功"})


@api_routes.route("/owner", methods=["DELETE"])
@certification(auth=True, role="admin")
def func_owner_delete_api():
    """
    根据owner ID 删除数据
    http://127.0.0.1:8080/api/owner
    Content-Type=application/json
    methods=["DELETE"]
    {
    "owner_id"   int     ***   数据库 ID
    }
    :return:
        {'status': 200, "msg": "删除成功"}
    ---
    tags:
      - 班次管理
    """
    data: dict = request.get_json()
    owner_id: str = data.get("owner_id")
    db_owner: Union[Owner, None] = g.session.query(Owner).filter(Owner.id == owner_id).first()
    if db_owner is not None:
        context_logs(name="删除排班", obsolescence=db_owner.__repr__(), data=None)

    g.session.query(Owner).filter(Owner.id == owner_id).delete()
    g.session.commit()
    return jsonify({'status': 200, "msg": "删除成功"})
